package com.vastio.boot.config;

import com.vastio.boot.filter.ApiFilter;
import com.vastio.boot.realm.MyRealm;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;

import javax.servlet.Filter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author hjwStart
 * @time 2022-12-01 10:59
 * @version: 1.0
 */
@Configuration
public class ShiroConfig {

    // 注意：SpringBoot中，如何通过@Bean创建了过滤器，
    // ShiroFilterFactoryBean必须是第一个创建的Bean
    @Bean
    public ShiroFilterFactoryBean shiroFilter() {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager());
        // 设置权限不足前往的访问页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/unAuth");
        // 设置登录表单页面（将Shrio提供的所有的过滤器的登录页面都设置为 /login.html），默认寻找/WEB-INF/login.jsp页面
//        shiroFilterFactoryBean.setLoginUrl("/login.html");
        Map<String, Filter> filters = new LinkedHashMap<>();
        // 重写的过滤器需要添加到filters中，覆盖默认的过滤器
        filters.put("api",new ApiFilter());
        filters.put("authc", authc());
        shiroFilterFactoryBean.setFilters(filters);
        ClassPathResource resource = new ClassPathResource("auth.properties");
        String filterChainStr = null;
        try {
            InputStreamReader isr = new InputStreamReader(resource.getInputStream());
            filterChainStr = FileCopyUtils.copyToString(isr);
        } catch (IOException e) {
            e.printStackTrace();
        }
        shiroFilterFactoryBean.setFilterChainDefinitions(filterChainStr);
        return shiroFilterFactoryBean;
    }

    private FormAuthenticationFilter authc() {
        FormAuthenticationFilter authc = new FormAuthenticationFilter();
        authc.setUsernameParam("userName");
        authc.setPasswordParam("userPwd");
        // 设置登录页面（默认登录页面是WEB-INF下的login.jsp）
        authc.setLoginUrl("/login.html");
        return authc;

    }

    @Bean("securityManager")
    public DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setSessionManager(mySessionManager());
        securityManager.setRealm(realm());
        return securityManager;

    }

    //创建DefaultWebSessionManager类
    @Bean
    public DefaultWebSessionManager mySessionManager() {
        DefaultWebSessionManager defaultSessionManager = new DefaultWebSessionManager();
        //将sessionIdUrlRewritingEnabled属性设置成false
        defaultSessionManager.setSessionIdUrlRewritingEnabled(false);
        return defaultSessionManager;
    }


    @Bean("myRealm")
    public Realm realm() {
        MyRealm myRealm = new MyRealm();
        myRealm.setCredentialsMatcher(credentialsMatcher());
        return myRealm;
    }

    @Bean("credentialsMatcher")
    public CredentialsMatcher credentialsMatcher() {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher("MD5");
        matcher.setHashIterations(1024);
        return matcher;
    }
}
